const app = getApp();
var db = wx.cloud.database({
  env: "lemonbox-t-6wew9"
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    thing: {},
    good: {},
    avatarUrl: '',
    userInfo: {},
    logged: false,
    rate: 4,
    content: '',
    commentList: [],
    openid: '',
    isComment: false,
    thingId:null,
    datearray: ['5天', '10天', '1个月', '3个月', '6个月', '9个月', '1年', '18个月', '2年'],
    s:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const id = options.id
    this.setData({
      thingId:id
    })
  },

  addComment: function (e) {
    console.log(e)
    var that = this
    if (e.detail.userInfo) {
      this.setData({
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }

    const self = this.data
    if (self.content == '') {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
      return
    }


    console.log(self)
    const good = this.data.good
    wx.showLoading({
      title: '正在检查文本',
    })

    wx.serviceMarket.invokeService({
      service: 'wxee446d7507c68b11',
      api: 'msgSecCheck',
      data: {
        "Action": "TextApproval",
        "Text": self.content
      },
      success: function (res) {

        console.log(res)
        if (res.data.Response.EvilTokens.length == 0) {
          db.collection('comment').add({
            data: {
              barcode: good.barcode,
              user: self.userInfo,
              content: self.content,
              rate: self.rate,
              createTime: new Date().getTime()
            },
            success: function (res) {
              that.setData({
                isComment: true
              })
              db.collection('comment').where({
                  barcode: that.data.good.barcode
                }).orderBy("createTime", "desc")
                .get({
                  success: function (res) {
                    wx.hideLoading({
                      success: (res) => {},
                    })
                    that.setData({
                      commentList: res.data
                    })
                  }
                })
            }

          })
        } else {
          wx.showToast({
            title: '文本违规',
            icon: 'none'
          })
        }



      }
    })



  },
  edit:function(e){
      console.log(e)
      wx.navigateTo({
        url: '/pages/addthing/addthing?id='+e.target.dataset.id,
      })
  },
  del:function(e){
    var that = this
    console.log(e)
    wx.showModal({
      title: '提示',
      content: '确定删除物品？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.showLoading({
            title: '正在删除',
          })
          db.collection('thing').doc(e.target.dataset.id).remove({
            success: function (res) {
              wx.hideLoading({
                success: (res) => {},
              })
              wx.navigateBack({
                delta: 1,
              })
            },
            fail:function (res){
             console.log(res)
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  delComment: function (e) {
    var that = this
    console.log(e)
    wx.showModal({
      title: '提示',
      content: '确定删除评论？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.showLoading({
            title: '正在删除',
          })
          db.collection('comment').doc(e.currentTarget.dataset.id).remove({
            success: function (res) {
              wx.hideLoading({
                success: (res) => {},
              })
              that.setData({
                isComment: false
              })
              console.log(that.data.good.barcode)
              db.collection('comment').where({
                  barcode: that.data.good.barcode
                }).orderBy("createTime", "desc")
                .get({
                  success: function (res) {
                    that.setData({
                      commentList: res.data
                    })
                  }
                })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  onContentChange: function (e) {
    this.setData({
      content: e.detail.value
    })
  },
  onRateChange:function(e){
    this.setData({
      rate:e.detail.score
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this

    this.setData({
      openid: app.globalData.openid
    })
    wx.showLoading({
      title: '正在加载',
    })
    const id = this.data.thingId
    db.collection('thing').doc(id).get({
      success: function (res) {
        console.log(res)
        wx.hideLoading({
          success: (res) => {},
        })
        that.setData({
          thing: res.data
        })
        if (res.data.barcode) {
          db.collection('good').where({
            barcode: res.data.barcode
          }).get({
            success: function (res) {
              that.setData({
                good: res.data[0]
              })
              db.collection('comment').where({
                  barcode: res.data[0].barcode
                }).orderBy("createTime", "desc")
                .get({
                  success: function (res) {
                    that.setData({
                      commentList: res.data
                    })
                    var tRate = 0
                    for (var idx in res.data) {
                      if (that.data.openid == res.data[idx]._openid) {
                        that.setData({
                          isComment: true
                        })
                      }
                      tRate += res.data[idx].rate
                    }
                    that.setData({
                      tRate:(tRate/res.data.length).toFixed(1)
                    })
                    console.log(that.data.tRate)
                  }
                })
            }
          })
        }
      }
    })
  },

  preview:function(e){
    if(e.target.dataset.img){
      wx.previewImage({
        urls: [e.target.dataset.img],
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return{
      title:'物品收纳提醒实用工具',
      imageUrl:'https://website-178c6e-1252504509.tcloudbaseapp.com/images/lemonbox/sharecover.png',
      path:"/pages/index/index"
    }
  }
})